// src/components/core/Navigation.tsx 导航栏组件
import React, { useContext, useEffect } from 'react'
import { Badge, Menu } from 'antd'
import { Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { AppState } from '../../store/reducers'
import { RouterState } from 'connected-react-router'
import { isAuth } from '../../helpers/auth'
import { Jwt } from '../../store/models/auth'
import { TotelContext } from '../../anotherStore'
import { itemCount } from '../../helpers/cart'

// 判断当前路由地址是否为所选地址 如果是则返回被选中的类名
function useActive (currentPath: string, path: string): string {
    // ant-menu-item-selected 导航被选中的类名
    return currentPath === path ? "ant-menu-item-selected" : ""
}

const Navigation = () => {
    const router = useSelector<AppState, RouterState>(state => state.router)
    // 获取当前的路由地址
    const pathname = router.location.pathname
    const isHome = useActive(pathname, '/')
    const isShop = useActive(pathname, '/shop')
    const isCart = useActive(pathname, '/cart')
    const isSignin = useActive(pathname, '/signin')
    const isSignup = useActive(pathname, '/signup')
    const isDashboard = useActive(pathname, getDashboardUrl())

    const [count, setCount] = useContext(TotelContext)

    // 只要数据变化就重新获取
    useEffect(() => {
        setCount(itemCount())
    })

    function getDashboardUrl () {
        let url = '/user/dashboard'
        if (isAuth()) {
            const {user: {role}} = isAuth() as Jwt
            if (role === 1) url = "/admin/dashboard"
        }
        return url
    }
    return (
        // mode: horizontal 横向  selectable 是否选中当前路由
        <Menu mode="horizontal" selectable={false}>
            <Menu.Item className={isHome}>
                <Link to="/">首页</Link>
            </Menu.Item>
            <Menu.Item className={isShop}>
                <Link to="/shop">商城</Link>
            </Menu.Item>
            <Menu.Item className={isCart}>
                <Link to="/cart">
                    购物车
                    <Badge count={count} offset={[5, -10]}/>
                </Link>
            </Menu.Item>
            {
                // 在未登录时显示 登录及注册导航
                !isAuth() && (
                <>
                    <Menu.Item className={isSignin}>
                        <Link to="/signin">登录</Link>
                    </Menu.Item>
                    <Menu.Item className={isSignup}>
                        <Link to="/signup">注册</Link>
                    </Menu.Item>
                </>
                )
            }
            {
                // 在登录时显示 dashboard 导航 
                // 且 dashboard 导航的路由地址根据用户的 role 状态发生改变
                isAuth() && (
                    <Menu.Item className={isDashboard}>
                        <Link to={getDashboardUrl()}>dashboard</Link>
                    </Menu.Item>
                )
            }
            
        </Menu>
    )
}

export default Navigation